﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Collections.ObjectModel;
using System.Windows.Data;

namespace XWord.WPF.Behaviors
{
    public class HistorySelectedBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            _historyList = new ObservableCollection<object>();
            TargetSelector.SelectionChanged += new SelectionChangedEventHandler(TargetSelector_SelectionChanged);
            AssociatedObject.SetBinding(Selector.ItemsSourceProperty, new Binding() { Source = _historyList });
            base.OnAttached();
        }

        void TargetSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                foreach (var item in e.AddedItems)
                {
                    if (_historyList.Count == 20)
                        _historyList.RemoveAt(19);
                    if (_historyList.Contains(item))
                    {
                        _historyList.Remove(item);
                       
                    }
                    _historyList.Insert(0, item);
                }
            }
        }

        private ObservableCollection<object> _historyList;

        public Selector TargetSelector
        {
            get { return (Selector)GetValue(TargetSelectorProperty); }
            set { SetValue(TargetSelectorProperty, value); }
        }

        public static readonly DependencyProperty TargetSelectorProperty =
            DependencyProperty.Register("TargetSelector", typeof(Selector), typeof(HistorySelectedBehavior), 
            new UIPropertyMetadata(null));

        
    }
}
